package club.ruanx.movie.schedule;

import club.ruanx.movie.entity.Movie;
import club.ruanx.movie.message.RabbitMessageReceiver;
import club.ruanx.movie.service.MovieService;
import club.ruanx.movie.util.SolrUpdater;
import club.ruanx.redis.entity.MessageData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author 阮胜
 * @date 2019/2/19 17:50
 */
@Component
@Slf4j
public class SpiderSyncScheduleTask {
    private static final long ONE_DAY = 1000 * 60 * 60 * 24;
    private final MovieService movieService;
    private final SolrUpdater solrUpdater;
    private final RabbitMessageReceiver rabbitMessageReceiver;
    private static Date tmpDate = new Date();

    public SpiderSyncScheduleTask(MovieService movieService, SolrUpdater solrUpdater, RabbitMessageReceiver rabbitMessageReceiver) {
        this.movieService = movieService;
        this.solrUpdater = solrUpdater;
        this.rabbitMessageReceiver = rabbitMessageReceiver;
    }

    /**
     * 每隔24小时执行一次
     */
    @Scheduled(fixedDelay = ONE_DAY)
    public void syncSolrMovies() {
        if (!isPass()) {
            return;
        }
        log.info("开始执行定时任务：同步搜索引擎数据");
        List<Movie> movies = movieService.findAll();
        int count = 0;
        for (Movie movie : movies) {
            try {
                solrUpdater.updateToSolrServer(movie);
                count++;
            } catch (Exception e) {
                //ignore
            }
        }
        log.info("定时任务：同步{}条数据成功", count);
    }

    @Scheduled(fixedDelay = ONE_DAY)
    public void syncSpiderMovies() {
        if (!isPass()) {
            return;
        }
        log.info("开始执行定时任务：同步爬虫数据");
        rabbitMessageReceiver.receive(MessageData.builder().build());
    }

    private boolean isPass() {
        if (DateUtils.addHours(tmpDate, 23).before(new Date())) {
            tmpDate = new Date();
            return true;
        }
        return false;
    }
}
